package com.mobi.Survey.lib.activities;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;

import com.mobi.Survey.lib.R;
import com.mobi.Survey.lib.model.SurveyDetailPojo;
import com.mobi.Survey.lib.uicomponents.ControlFactory;
import com.mobi.Survey.lib.utils.Device;
import com.mobi.Survey.lib.utils.Helper;
import com.mobi.Survey.lib.video.VideoPlayer;

public class SurveyDetailAllControls extends AbstractDetailScreen
{
	private List<Bitmap> bitmapsProduc = new ArrayList<Bitmap>();
	private List<ImageView> ivsProduct = new ArrayList<ImageView>();

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}

	ScrollView components;

	@Override
	protected void onEmptyFieldException(int controlIndex)
	{
		components.smoothScrollTo(0, views.get(controlIndex).getTop());
	}

	protected void createViews()
	{

		ViewGroup vg = (ViewGroup) findViewById(R.id.llSurveyDetailSingle);
		boolean haveInputField = false;
		
		if (vg != null && sdps != null && sdps.size() > 0)
		{

			// boolean firstImage = true;
			for (SurveyDetailPojo sdp : sdps)
			{
				if(!haveInputField){
					haveInputField = ControlFactory.isInputControl(sdp);
				}
				
				View v = ControlFactory.createControl(sdp, this, true);
				if (v == null)
				{
					printLogMessage("Invalid Control Found with Control No: "
							+ sdp.getControlType());
					continue;
				}

				// if control type is Video View perform necessary action on
				// video control
				if (sdp.getControlType() == ControlFactory.CONTROL_VIDEO_VIEW)
				{

					performActionOnVideoControl(sdp, v);

				}

				if (sdp.getControlType() == ControlFactory.CONTROL_IMAGE_VIEW)
				{

					performActionOnImageControl(sdp, v);

				}

				vg.addView(v);
				views.add(v);

			}
		
			
			
			if (haveInputField) {
				btnSubmit = new Button(this);
				btnSubmit.setWidth(Device.getInstance().getPercentWidth(1f));
				btnSubmit.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						v.setId(R.id.btnSubmit);
						btnClick(v);

					}
				});
				btnSubmit.setText("Submit");
				btnSubmit.setPadding(0, 15, 0, 10);
				vg.addView(btnSubmit);
			}
			
			new DownloadImageFile().execute();

		}

		else
		{
			// printMessage("View Group Null Include header");
			showShortToast(Messages.NO_SURVEY_DETAIL);
		}
	}

	@Override
	protected int getLayoutId()
	{
		// TODO Auto-generated method stub
		return LayoutIds.DETAIL_SCREEN_ALL_CONTROLS;
	}

	@Override
	protected void initUiVars()
	{

		super.initUiVars();
		components = (ScrollView) findViewById(R.id.sv);

	}

	@Override
	protected void performActionOnVideoControl(
			SurveyDetailPojo surveyDetailPojo, View view)
	{

		String vid = surveyDetailPojo.getControlParameter1();
		videoUrls.add(vid);

		// If not single screen we have image views for preview of video control

		// If Single screen we have button for video control to let the user
		// open Video Screen
		int index = 0;
		if (surveyDetailPojo.getControlText() != null
				&& surveyDetailPojo.getControlText().length() > 0)
		{
			{
				index++;
			}

		}
		Button btn = (Button) ((ViewGroup) view).getChildAt(index);

		viewVids.add(btn);
		btn.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				int indexOf = viewVids.indexOf(v);
				String vidUrl = videoUrls.get(indexOf);

				if (vidUrl.contains("youtube"))
				{

					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setData(Uri.parse(vidUrl));
					startActivity(intent);
				} else
				{

					switchScreenTo(VideoScreen.class, VideoPlayer.TYPE_GENERIC
							+ vidUrl);
				}

			}
		});

	}

	private class DownloadImageFile extends AsyncTask<String, Integer, String>
	{

		private ProgressDialog mProgressDialog;

		// private String msg;

		protected void onPreExecute()
		{

			super.onPreExecute();

			mProgressDialog = new ProgressDialog(SurveyDetailAllControls.this);
			mProgressDialog.setMessage(Messages.DOWNLOAD_PRODUCT_IMGS);
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setCancelable(false);

			mProgressDialog.show();
		}

		protected String doInBackground(String... url)
		{

			try
			{

				String imageUrl = survey.getbGImageUrl();
				if (null != imageUrl && imageUrl.length() > 0)
				{

					String outputfile = Helper.getTempFile(Helper
							.getHashNameFromUrl(imageUrl) + "");
					if (!new File(outputfile).exists())
						Helper.downloadFile(imageUrl, outputfile);

					survey.setBgImageBitmap(Helper.decode(outputfile, 3));
				}
			} catch (Exception e)
			{

			}
			int size = imageUrls.size();
			// for each image url and video(Preview image of video) we will
			// download that image and save it in
			// application specific directory
			// with name of Hash code which we calculate from url
			// if a file with same hash code already exist we don't download
			for (int i = 0; i < size; i++)
			{
				String imgUrl = imageUrls.get(i);

				int imgHashName = Helper.getHashNameFromUrl(imgUrl);
				Bitmap b = null;
				String local = Helper.getTempFile(imgHashName + "");

				if (Helper.isFileExist(local))
				{
					b = Helper.decode150x150(local, 1);

				} else
				{
					try
					{
						Helper.downloadFile(imgUrl, local);
						b = Helper.decode150x150(local, 1);

					} catch (IOException e)
					{

						printMessage("Helper.downloadFile(imgProductUrl, productImgPath)");

					}

				}

				bitmapsProduc.add(b);

			}
			// If video type is youtube we get preview image from youtube using
			// http://i.ytimg.com/vi/" + Youtube Video Id + "/0.jpg
			// If video type is any other we don't have preview image so we just
			// display no preview image from resource

			return null;
		}

		protected void onPostExecute(String result)
		{

			super.onPostExecute(result);

			if (survey.getBgImageBitmap() != null
					&& !survey.getBgImageBitmap().isRecycled())
			{

				ivBgImage.setBackgroundDrawable(new BitmapDrawable(survey
						.getBgImageBitmap()));

			} else
			{
				ivBgImage.setVisibility(View.GONE);
			}

			int size = ivsProduct.size();
			for (int i = 0; i < size; i++)
			{
				ImageView ivProduct = ivsProduct.get(i);
				Bitmap product = bitmapsProduc.get(i);

				if (ivProduct != null)
				{
					if (product != null)
					{
						ivProduct.setImageBitmap(product);
					} else
					{
						ivProduct.setImageResource(R.drawable.nopreview);
					}
				}
			}
			mProgressDialog.dismiss();
			mProgressDialog = null;

		}

		protected void onProgressUpdate(Integer... values)
		{

			super.onProgressUpdate(values);

			if (values[0] == 50)
				mProgressDialog
						.setMessage(Messages.DOWNLOADING_VIDEO_PREVIEW_IMG);

		}

	}

	@Override
	protected void performActionOnImageControl(
			SurveyDetailPojo surveyDetailPojo, View view)
	{

		String imgUrl = surveyDetailPojo.getControlParameter1();
		imageUrls.add(imgUrl);

		int index = 0;
		if (surveyDetailPojo.getControlText() != null
				&& surveyDetailPojo.getControlText().length() > 0)
		{
			{
				index++;
			}

		}
		ImageView v = (ImageView) ((ViewGroup) view).getChildAt(index);
		ivsProduct.add(v);
	}

	@Override
	protected void onRelease()
	{
		headerImage.setBackgroundDrawable(null);

		if (null != survey)
		{
			survey.getSurveyDetail().clear();

			if (survey.getBgImageBitmap() != null
					&& !survey.getBgImageBitmap().isRecycled())
			{
				survey.getBgImageBitmap().recycle();
				survey.setBgImageBitmap(null);
			}
			survey = null;

		}
		if (sdps != null)
		{
			sdps.clear();
		}

		if (null != views)
		{
			views.clear();
			views = null;
		}

		if (null != ivsProduct)
		{
			for (ImageView iv : ivsProduct)
			{
				iv.setImageBitmap(null);
				iv.setBackgroundDrawable(null);
			}
			ivsProduct.clear();
			ivsProduct = null;
		}
		ivBgImage.setBackgroundDrawable(null);

		if (null != bitmapsProduc)
		{
			for (Bitmap b : bitmapsProduc)
			{
				if (b != null)
				{
					b.recycle();
				}
			}

			bitmapsProduc.clear();
			bitmapsProduc = null;
		}

	}
}
